package es.upv.epsa.mobweb.moneyback;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.ObjectMapper;

import es.upv.epsa.mobweb.moneyback.database.User;
import es.upv.epsa.mobweb.moneyback.json.JSONParser;

public class UserLoginActivity extends Activity {
	private EditText 	editUser;
	private EditText 	editPassword;
	private Button		btnLogin;
	private TextView	txtSignUp;
	
	private String		server_url;
	private JSONParser 	jsonParser;
	
	private ObjectMapper  		mapper = new ObjectMapper();
	
	private MainApplication	  	app;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_login);
		
		jsonParser = new JSONParser();
		setWidgets();
		checkUserLoggedIn();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	
	private void setWidgets(){
		server_url		= getResources().getString(R.string.server_url) +
				  		  getResources().getString(R.string.users_url);
		
		app				= (MainApplication) getApplication();
		
		editUser 		= (EditText) 	findViewById(R.id.editUser);
		editPassword 	= (EditText) 	findViewById(R.id.editPassword);
		btnLogin		= (Button) 		findViewById(R.id.btnLogin);
		txtSignUp		= (TextView)	findViewById(R.id.txtSignup);
		
		editUser.setText("juanvi");
		editPassword.setText("0000");
		
		btnLogin.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View view) {
				String user = editUser.getText().toString();
				String pass = editPassword.getText().toString();
				
				if(user == null || pass == null)
					return;
				
				loginUser(user, pass);
			}
			
		});
		
		txtSignUp.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), RegisterActivity.class);
				
				startActivity(intent);
			}
			
		});
	}
	
	/**
     * function make Login Request
     * @param email
     * @param password
     * */
    private void loginUser(String user, String password){
    	JsonFactory 			jfactory 	= new JsonFactory();
		ByteArrayOutputStream 	bout 		= new ByteArrayOutputStream();
		JsonGenerator 			jGenerator;
		
		try {
			jGenerator = jfactory.createJsonGenerator(new OutputStreamWriter(bout, "UTF-8"));
			jGenerator.writeStartObject();

			jGenerator.writeNumberField("action", 0);
			jGenerator.writeStringField("username", user);
			jGenerator.writeStringField("password", password);
			
			jGenerator.writeEndObject();
			jGenerator.close();
			
			new SendJSON(bout.toString()).execute();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    /**
     * Implemented with Jackson parser
     */
    private void parseJSON(String json){
    	try {
    		User u = new User();
    		JsonFactory jfactory = new JsonFactory();
    		JsonParser jparser = jfactory.createJsonParser(json);
    		
    		while(jparser.nextToken() == JsonToken.START_OBJECT)
    		   u = mapper.readValue(jparser, User.class);
    		
    		app.setUser(u);
    		
    		jparser.close();
    		
    		Intent intent = new Intent();
    		//
    		intent.setClass(getApplicationContext(), MainMenuActivity.class);
    		startActivity(intent);
		} catch (JsonParseException e) {
			Toast.makeText(getApplicationContext(), "Incorrect username or password...", Toast.LENGTH_LONG).show();
			//e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
	
	// Checks if the user has already logged in with username and password
	// If logged in, skip this screen and load the MainMenuActivity
	private void checkUserLoggedIn(){
		if(app.getUser().getId() != -1){
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), MainMenuActivity.class);
			startActivity(intent);
		}
	}
	
	private class SendJSON extends AsyncTask<Void, Void, Void>{
		String 			json 	= "";
		String 			data 	= "";
		ProgressDialog 	dialog;
		
		public SendJSON(String json){
			this.json = json;
		}
		
		@Override
		protected Void doInBackground(Void... arg0) {
			data = jsonParser.sendJSON(server_url, json);
			
			return null;
		}
		
		@Override
		protected void onPreExecute(){
			dialog = ProgressDialog.show(UserLoginActivity.this, "", UserLoginActivity.this.getResources().getString(R.string.logging_in), true);
			dialog.setCancelable(false);
			dialog.setOnCancelListener(new OnCancelListener(){

				@Override
				public void onCancel(DialogInterface dialog) {

				}
				
			});
		}
		
		@Override
		protected void onPostExecute(Void result){
			parseJSON(data);
			dialog.dismiss();
		}
	}
}
